/**
 * Created by zhanglihe on 15/11/17.
 */
require.config(require_config);

define([
    'jquery',
    'common',
    'ready',
    'template',
    'model',
    'dialog'
], function( $, common, ready, template, Model, dialog ) {

    loading();
    var id = getUrlPath(4);
    var index = function() {
        this.init();
    };
    index.prototype = {
        init: function() {
            var _this = this;
            $.ajax({
                url: _global.url.api + 'resource',
                type: 'get',
                async: false,
                data: {tree: 1, type: 5},
                success: function(res) {
                    _this.resource = res.code == 0 ? res.data : [];
                }
            });

            this.event();
            this.fetch();
        },

        fetch: function() {
            var _this = this;
            this.model = new Model({
                url: _global.url.api + 'admin/' + id,
                sync: function() {
                    var model = this;
                    //是否选中状态
                    if(model.data.resource) {
                        $.each(_this.resource, function() {
                            this.checked = model.data.resource.indexOf(this.id) > -1;
                            if(typeof this.child !== 'undefined') {
                                $.each(this.child, function() {
                                    this.checked = model.data.resource.indexOf(this.id) > -1;
                                })
                            }
                        });
                    }
                    $('#data-list').html(template('resource-tpl', {resource: _this.resource, admin: this.data}));
                },
                callback: function() {
                    loaded();
                }
            });
            this.model.fetch();
        },

        event: function() {
            var _this = this;
            $('#btn-save').on('click', function(e) {
                e.preventDefault();
                _this.save();
            });
            $('body').on('click', '.parent', function(e) {
                var id = $(this).attr('data-key');
                if(typeof _this.resource[id].child === 'undefined') {
                    return;
                }
                if($(e.target).is(':checked')) {
                    $('.child'+id).prop('checked', true);
                } else {
                    $('.child'+id).prop('checked', false);
                }
            });
        },
        save: function() {
            var resource = [];
            $.each($('[name="resource"]'), function() {
                if($(this).is(':checked')) {
                    resource.push($(this).val());
                }
            });
            this.model.formData = {resource: resource};
            this.model.put();
        }
    };

    new index();

});